package com.yonyougov.devops.cruxcisupport.component;

import com.yonyougov.devops.cruxcisupport.role.RoleEntity;
import com.yonyougov.devops.cruxcisupport.user.vo.JwtUser;
import com.yonyougov.devops.cruxcisupport.userrole.UserRoleEntity;
import com.yonyougov.devops.cruxcisupport.userrole.UserRoleService;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

@Component
public class UserStore {
    private InheritableThreadLocal<JwtUser> currentJwtUser = new InheritableThreadLocal<>();
    private UserRoleService userRoleService;

    public UserStore(UserRoleService userRoleService) {
        this.userRoleService = userRoleService;
    }

    public void setCurrentJwtUser(JwtUser user) {
        currentJwtUser.set(user);
    }

    public JwtUser getCurrentUser() {
        return currentJwtUser.get();
    }

    public void removeCurrentUser() {
        currentJwtUser.remove();
    }

    public List<RoleEntity> currentUserRoles() {
        if (getCurrentUser() != null) {
            UserRoleEntity userRoleCond = new UserRoleEntity();
            userRoleCond.setUserId(getCurrentUser().getId());
            return userRoleService.findAllByUserId(userRoleCond.getUserId());
        }
        return Collections.EMPTY_LIST;
    }
}
